﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FacturIT.Service.Enum;

namespace FacturIT.BLL.Model.Helper
{
    public static class OrderHelper
    {
        public static IEnumerable<T1> ApplyOrdering<T1, T2>(IEnumerable<T1> query, IDictionary<Func<T1, T2>, Ordering> columns, Func<T1, T2> defaultOrdering)
        {
            Service.Enum.Ordering order;
            Func<T1, T2> ordering;

            var enumerator = columns.GetEnumerator();
            IOrderedEnumerable<T1> orderedQuery = query.OrderBy(defaultOrdering); //TODO: changae predicate, takes unneeded resources

            if (enumerator.MoveNext()) //primaire sortering (1)
            {
                ordering = enumerator.Current.Key;
                order = enumerator.Current.Value;
                switch (order)
                {
                    case Service.Enum.Ordering.Ascending:
                        orderedQuery = query.OrderBy(ordering);
                        break;
                    case Service.Enum.Ordering.Descending:
                        orderedQuery = query.OrderByDescending(ordering);
                        break;
                    case Service.Enum.Ordering.None: break;
                    default: break;
                }
            }
            else return query.OrderBy(defaultOrdering); // default ordering... Mostly ID;

            while (enumerator.MoveNext()) //secundaire sorteringen (1>oo)
            {
                ordering = enumerator.Current.Key;
                order = enumerator.Current.Value;
                switch (order)
                {
                    case Service.Enum.Ordering.Ascending:
                        orderedQuery = orderedQuery.ThenBy(ordering);
                        break;
                    case Service.Enum.Ordering.Descending:
                        orderedQuery = orderedQuery.ThenByDescending(ordering);
                        break;
                    case Service.Enum.Ordering.None: break;
                    default: break;
                }
            }

            return orderedQuery;
        }
    }
}
